<script setup lang="ts">
import { ref, PropType, watch, unref } from 'vue'
import { ElInput, ElTree } from 'element-plus'
import { propTypes } from '@/utils/propTypes'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
const dialogTitle = ref('参照（请双击选择）')
const dialogVisible = ref(false)
const props = defineProps({
  title: {
    type: String as PropType<Nullable<string>>,
    default: () => '参照（请双击选择）'
  },
  modelValue: propTypes.string.def(''),
  modelName: propTypes.string.def(''),
  nameField: propTypes.string.def(''),
  relNameField: propTypes.string.def(''),
  tree: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  eId: propTypes.any.def()
})
console.log(props.eId, 'dId')
const treeRef = ref<ComponentRef<typeof ElTree>>()

// 输入框的值
const valueRef = ref(props.modelValue)
const nameRef = ref(props.modelName)

watch(
  () => props.modelValue,
  (val: string) => {
    if (val == '') {
      nameRef.value = ''
    }
    if (val === unref(valueRef)) return
    valueRef.value = val
  }
)

watch(
  () => props.modelName,
  (val: string) => {
    if (val === unref(nameRef)) return
    nameRef.value = val
  }
)

watch(
  () => props.title,
  (value) => {
    if (!value) return
    dialogTitle.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

const emit = defineEmits(['update:modelValue', 'change', 'modelName'])

const save = async (a) => {
  nameRef.value = a.name
  valueRef.value = a.id
  let value = a.this_asset_count
  emit('change', [valueRef.value, nameRef.value, value, props.eId])
  emit('update:modelValue', valueRef.value)
  emit('modelName', nameRef.value)
  dialogVisible.value = false
}
const onDialog = () => {
  dialogVisible.value = true
}

const onChange = (value) => {
  if (value == '') {
    emit('update:modelValue', '')
  }
}

defineExpose({
  getForm() {
    return { ids: treeRef.value!.getCheckedKeys() }
  }
})
</script>

<template>
  <div>
    <ElInput v-model="valueRef" type="hidden" />
    <ElInput
      @click="onDialog()"
      v-model="nameRef"
      placeholder="点击选择"
      v-bind="$attrs"
      @change="onChange"
    >
      <template #suffix> <Icon @click="onDialog()" icon="ep:search" /> </template>
    </ElInput>
    <Dialog v-model="dialogVisible" :title="dialogTitle" :append-to-body="true">
      <ElTree
        ref="treeRef"
        :data="props.tree"
        :props="{ children: 'children', label: 'name' }"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
        check-strictly
        @node-click="save"
      />
    </Dialog>
  </div>
</template>
